<?php

require_once 'lib/business/main.php';

class Page extends BasePage {
  // the following has hardcoded user and page for now
  // - to make things easy and workable
  // - it should obviously be changed to something dynamic like either in-page data or $_SESSION data
  // - the page number should also be tied to the users_pages.id column
  const SCRIPTS = '
<script type="text/javascript">
  $(document).ready(function() {
    try{
      $(".drop_widget_add").droppable({
        accept: \'.draggable_widget_add\',
        drop: function(ev,ui){
            linkWidget($(this),0,ui.draggable,true);
        }
      });
    }catch(err){
      alert(err);
    }
    try{
      $(".draggable_widget_add").draggable({
          revert: true,
          cursor: \'move\',
          opacity: 0.7,
          helper: \'clone\'
      });
    }catch(err){
      alert(err);
    }
    try{
      $(".drop_widget_remove").droppable({
        accept: \'.draggable_widget_remove\',
        drop: function(ev,ui){
            linkWidget($(this),0,ui.draggable,false);
        }
      });
    }catch(err){
      alert(err);
    }
    try{
      $(".draggable_widget_remove").draggable({
          revert: true,
          cursor: \'move\',
          opacity: 0.7,
          helper: \'clone\'
      });
    }catch(err){
      alert(err);
    }
    function linkWidget(data_row,data_id,widget_div,adding) {
      if(!data_id) {
        data_id = widget_div.attr("id");
      }
      var link = widget_div.find(\'h2\');
      var widget_num = link.html();
      var confirm_msg = "";
      if(adding) {
        confirm_msg = "You are about to ADD "+widget_num+".\nAre you sure you want to do this?";
      } else {
        confirm_msg = "You are about to REMOVE "+widget_num+".\nAre you sure you want to do this?";
      }
      if(confirm(confirm_msg)){
        $.post(
            "index.php?p=link",
            {widget: data_id, page: 1, user: 1, add: adding},
            function(data) {
              if(data.indexOf("<!DOCTYPE") == 0) {
                alert("Error");
              } else {
                if(data.indexOf(\'<div class="failure\') == 0) { // did not fail
                  $(data).appendTo("#view");
                } else {
                  var resp;
                  if(data.indexOf("{\\"data\":") == 0) { // JSON
                    resp = jQuery.parseJSON(data);
                  } else {
                    resp = data;
                    msg = resp;
                  }
                  var msg;
                  var id;
                  if(resp["data"]) {
                    msg = unescape(resp["data"]);
                  }
                  if(resp["id"]) {
                    id = resp["id"];
                  }
                  $(msg).appendTo("#view");
                  // only fade it out if it was removed
                  if(!adding) {
                    widget_div.fadeOut();
                  } else {
                    var newdiv = widget_div.clone();
                    if(id) {
                      newdiv.addClass("draggable_widget_remove");
                      newdiv.attr("id","widget_remove"+id);
                    }
                    try{
                      newdiv.removeClass("draggable_widget_add").appendTo(data_row);
                      newdiv.draggable({
                          revert: true,
                          cursor: \'move\',
                          opacity: 0.7,
                          helper: \'clone\'
                      });
                    }catch(err){
                      alert(err);
                    }
                  }
                }
              }
            }
        ); 
      }
    }
  });
</script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>';
  const CSS = '
<link media="all" href="css/config_widgets.css" rel="stylesheet" type="text/css" ></link>';
  const AVAILABLE_WIDGETS_TOKEN = '<!-- available_widgets -->';
  const CURRENT_WIDGETS_TOKEN = '<!-- current_widgets -->';

  function __construct($database) {
    parent::__construct($database);
    $this->scripts .= $this::SCRIPTS;
    $this->css .= $this::CSS;
  }

  function tinkle($content = '') {
    // returns FALSE if the file is not found
    if($template = file_get_contents('templates/config_widgets.inc')) {
      $template = $this->_add_available_widgets($template);
      $template = $this->_add_current_widgets($template);
      //error_log("config_widgets->tinkle(): read template: {$template}");
      // spit it out 
      parent::tinkle($template);
    } else {
      //error_log("config_widgets->tinkle(): could not read template");
      parent::tinkle();
    }
  }

  function set_language($new_lang) {
    // TODO this could probably be done better with some kind of event registration instead
    if(parent::set_language($new_lang)
        && file_exists("lib/l10n/{$this->language}/config_widgets.php")
        && is_readable("lib/l10n/{$this->language}/config_widgets.php")) {
      // language was changed, update localized items
      $this->language_file = "lib/l10n/{$this->language}/config_widgets.php";
      // fills $tmp_language_strings
      include_once "lib/l10n/{$this->language}/config_widgets.php";
      //error_log("tmp_language_strings: ".print_r($tmp_language_strings,true));
      // make the parent class add these language items - overriding them as needed
      $this->add_language_strings($tmp_language_strings);
    } else {
      //error_log('config_widgets.set_language(): Could not set new language - '.$new_lang);
    }
  }

  function output_callback($output) {
    //error_log("config_widget->output_callback(): $output");
     return parent::output_callback($output);
  }

  private function _add_current_widgets($s) {
    // not worrying about improving this SQL using JOIN or aliases
    if((strpos($s, $this::CURRENT_WIDGETS_TOKEN) > 0)
        && ($res = $this->db->query("SELECT users_widgets.widget, users_widgets.id"
            . " FROM users_widgets, users, users_pages"
            . " WHERE ((users_widgets.enabled =1) AND (users.id =1) AND (users_pages.page = 'config_widgets'))"
            . " ORDER BY users_widgets.widget ASC , users_pages.page ASC"
            . " LIMIT 0 , 30"))) {
      $tmp = '';
      while($row = $res->fetch_assoc()) {
        $widget = $row['widget'];
        if(file_exists("lib/widgets/{$widget}.php") && is_readable("lib/widgets/{$widget}.php")) {
          // TODO this whole section could be improved by storing the HTML in the database and updating it nightly/weekly
          include_once "lib/widgets/{$widget}.php";
          $reflection = new ReflectionClass( $widget );
          // don't pass any values at this point because that's no implemented yet
          $instance = $reflection->newInstance( );
          $tmp .= '<div class="draggable_widget_remove" id="widget_remove'.$row['id'].'">'.$instance->to_string().'</div>';
        }
      }
      $res->free_result();
      if(empty($tmp)) {
        // TODO this should be in its own class and/or function to make it standard for all messages
        $tmp = '<div class="failure"><!-- error_no_current_widgets --></div>';
      }
      //error_log("tmp: ".$tmp);
      $s = str_replace($this::CURRENT_WIDGETS_TOKEN, $tmp, $s);
    }
    return $s;
  }

  private function _add_available_widgets($s) {
    if(strpos($s, $this::AVAILABLE_WIDGETS_TOKEN) > 0) {
      $tmp = '';
      if(is_readable('lib/widgets')) {
        if($files = scandir('lib/widgets')) {
          foreach($files as $file) {
            if(is_file('lib/widgets/'.$file) && strpos($file, '.') > 0) { // TODO should do more testing for file matching here: e.g., 'Widget*.php'
              // TODO this whole section could be improved by storing the HTML in the database and updating it nightly/weekly
              include_once 'lib/widgets/'.$file;
              $class_name = substr($file,0,strlen($file)-4); // get the file name without ".php"
              $reflection = new ReflectionClass( $class_name );
              // don't pass any values at this point, any configuration for the widget would be done at a later time
              $instance = $reflection->newInstance( );
              $tmp .= "\n<div class=\"draggable_widget_add\" id=\"{$class_name}\">".$instance->to_string().'</div>';
            }
          }
        }
      }
      if(empty($tmp)) {
        // TODO this should be in its own class and/or function to make it standard for all messages
        $tmp = '<li class="failure"><!-- error_no_widgets_available --></li>';
      }
      $s = str_replace($this::AVAILABLE_WIDGETS_TOKEN, $tmp, $s);
    }
    return $s;
  }
}
?>
